#!/usr/bin/perl
#
# Write a Web page about a place.
#
use Counter;
use strict;
use UNIVERSAL qw(isa); # to get type-check ability

# Config vars
use vars qw($maxdirect $minsub $prefix $date $recursion);
# Global exec vars
use vars qw($recno $places $persons $rec @toprint $pagemaster $legalurl);
# Keep track of loaded info about countries
use vars qw($competitionrankloaded $country @rank2id %rank);

# Constants that control recursion
$maxdirect = 30; # If "users" is more than this, subpages MAY be used
$minsub = 2; # If sub->"users" less than this, inline it anyway

$prefix = "test-www";
$legalurl = "/legal.php";

# Initialize variables
$date = gmtime();

while ($ARGV[0] =~ /^-/) {
    my $opt = shift;
    if ($opt eq "-R") {
	# Do recursion, write to generated filenames
	$recursion = 1;
    } elsif ($opt eq "-prefix") {
	$prefix = shift;
    } elsif ($opt eq "-minsub") {
	$minsub = shift() + 0;
    } elsif ($opt eq "-maxdirect") {
	$maxdirect = shift() + 0;
    } else {
	die "No option $opt\n";
    }
}
$recno = shift;
$places = FileTable::open("db/places");
$persons = FileTable::open("db/persons");

if ($recno =~ /^\d+/) {
    $rec = $places->get($recno);
} else {
    $rec = $places->getbykey("name", $recno);
}
die "No such place as $rec\n" if !$rec;

if ($recursion) {
    push(@toprint, $rec);
    while ($toprint[0]) {
	my $rec = shift(@toprint);
	my $left = $#toprint + 1;
	warn "Printing for $$rec{name}, $left left\n";
	emitfile($rec);
    }
} else {
    emitfile($rec);
    if ($#toprint > -1) {
	print STDERR "Subordinates to print:";
	for $rec (@toprint) {
	    print STDERR " ", $$rec{name};
	}
	print STDERR "\n";
    } else {
	warn "No subordinates worth printing\n";
    }
}
sub emitfile {
    my $rec = shift;
    my $level = 1;
    openfile($rec);
    my $subswritten = writesubs($rec, 2); # headers at <h2>
    my $count = usercount($rec);
    my $othercount = $persons->count("placeid = ?", $$rec{name});
    if ($subswritten > 0 && $othercount) {
	printf OUT "<h%d>Other users in $$rec{longname}</h%d>\n",
	$level + 1, $level + 1;
	print OUT "$othercount users\n";
    }
    listusers($rec);
    closefile($rec);
}

sub openfile {
# Write a page.
    my $rec = shift;
    my $filename;
    if ($recursion) {
	$filename =  "$prefix/" . urlify($$rec{name}) . ".php";
	open(OUT, ">$filename") || die "Unable to open $filename for write\n";
    } else {
	open(OUT,  ">&STDOUT");
    }

    # Set globally who's the page master
    $pagemaster = $rec;
    print OUT "<?php include \"counter2.php\"; ?>\n";
    print OUT "<?php pagestart(); ?>\n";
    print OUT "<html>\n";
    print OUT "<?php pagehead(_(\"Linux users in\") . \" $$rec{name}\") ?>\n";
    print OUT "<body bgcolor=white>\n";
    print OUT "<?php pagetop(_(\"Linux users in\") . \" $$rec{longname} ($$rec{name})\") ?>\n";

    print OUT "<font size=-2><a href=\"$legalurl\"><?php print _(\"Copyright &copy; Linux Counter Project. Usage restricted\") ?>.</a></font><br>\n";
    print OUT "<?php print _(\"This file generated\") ?>: $date<p>\n";
    # Print some country info
    if ($$rec{type} eq "country" || $$rec{type} eq "world") {
	# Plot of registrations - generated via "system" call (nekulturny!)
	my $imgname = "\L$$rec{name}.png";
	my $country = "$$rec{name}";
	print OUT "<img src=\"$imgname\"><p>\n";
	if ($recursion) {
	    system("tools/plothistory --png $country  < ../temp/country.story | gnuplot > $prefix/$imgname"); 
	}
    }
    # Notes from the placemaster
    if ($$rec{html}) {
	print OUT "<hr>\n";
	print OUT $$rec{html};
	print OUT "<hr>\n";
    }
    print OUT <<EoF;
<table border=0 width="80%">
<tr><td>
EoF
    maintainer($rec);
    print OUT "<?php print _(\"Population\") ?>: $$rec{population} <?php print _(\"million\") ?><br>\n"
	if $$rec{population};
    print OUT "<?php print _(\"Hostcount\") ?>: $$rec{hostcount}<br>\n"
	if $$rec{hostcount};
    if ($$rec{users}) {
	print OUT "<?php print _(\"Linux users\") ?>: $$rec{users}<br>\n";
    } else {
	warn "<?php print _(\"No users field in\") ?> ", $rec->key, "\n";
    }	
    if ($$rec{population} > 0) {
	my $density = $$rec{users} / $$rec{population};
	printf OUT "<?php print _(\"Linux density\") ?>: %5.2f <?php print _(\"users/million\") ?><br>\n", $density;
    }
    if ($$rec{hostcount} > 0) {
	printf OUT "<?php print _(\"Linux users per 1000 IP hosts\") ?>: %5.2f<br>\n",
	$$rec{users} * 1000 / $$rec{hostcount};
    }
    competitionrank($rec);
    print OUT <<EoF;
<td align=right>
<table border>
<tr><td><a href="/enter-person.php"><strong><font size=5>
<?php print _("Count me too") ?>!</font></strong></a>
</table>
</table>
EoF

}

sub closefile {

    print OUT "<?php pagebottom() ?>\n</body>\n</html>\n";
    close OUT if $recursion;
}

sub writesubs {
    # And now for the subordinates
    my $rec = shift;
    my $level = shift;
    my ($subrecid, $subrec, $subswritten);
    for $subrec ($places->select("within = ? order by longname", $rec->key)) {
	next if $$subrec{type} eq "alias";
	my $count = usercount($subrec);
	print OUT "<!-- placerec ", $subrec->key, " - $count users -->\n";
	if (($count > $minsub)
	     && $$pagemaster{users} > $maxdirect) {
	    print OUT "<h$level><a href=\"./",
	           urlify($$subrec{name}), ".php\">",
	              "$$subrec{longname}</a></h$level>\n";
	    print OUT "$count <?php print _(\"users\") ?>\n";
	    push(@toprint, $subrec);
	} elsif ($count) {
	    print OUT
		"<h$level>$$subrec{longname}</h$level>\n";
	    my $subsubswritten = writesubs($subrec, $level + 1);
	    if ($subsubswritten && $count) {
		printf OUT "<h%d>", $level + 1;
		print OUT "<?php print _(\"Other users in\") ?> $$subrec{longname}";
		printf OUT "</h%d>\n", $level + 1;
	    }
            print OUT "<!-- listing in $$subrec{name} -->\n";
	    listusers($subrec);
	    # Countries should be listed anyway....we need
	    # their files....
	    push(@toprint, $subrec) if $$subrec{type} eq "country";
	}
	++ $subswritten;
    }
    return $subswritten;
}

sub listusers {
    my $rec = shift;
    my ($userid, $person, $hidden);
    my $count = 0;
    print OUT "<ul>\n";
    my @recset = $persons->selectclean("placeid = ? order by name", $$rec{name});
    for $person (@recset) {
	++ $count;
	if (!$person) {
	    warn "Missing person in $$rec{name}: $person\n";
	    next;
	}
	if (!defined($person->{"may_publish"}) || $person->{"may_publish"} ne "YES") {
	    ++ $hidden;
	} else {
	    print OUT "<li><strong><a href=\"/cgi-bin/runscript/display-person.cgi?user=", $person->key(), "\">$$person{name}</a></strong></li>\n";
	}
    }
    print OUT "</ul>\n";
    if ($hidden == 1) {
        print OUT "$hidden <?php print _(\"person declined to be listed\") ?><br>\n";
    } elsif ($hidden > 1) {
        print OUT "$hidden <?php print _(\"persons declined to be listed\") ?><br>\n";
    }
}
    
sub urlify {
    my $str = shift;
    $str =~ s/[^a-zA-Z0-9-:]/_/g;
    $str =~ tr/A-Z/a-z/;
    substr($str, 0, 2) =~ tr/a-z/A-Z/;
    $str;
}

sub recsortby {
    my $recfile = shift;
    my $sortfield = shift;
    my @keys = @_;

    my @recs;
    my $ix;
    my $ix2;
    for $ix (0..$#keys) {
	push(@recs, $recfile->getclean($keys[$ix]));
	if (!$recs[$#recs]) {
	    warn "Missing record $ix: $keys[$ix]\n";
	    pop(@recs);
	}
    }
    return sort {$a->{$sortfield} cmp $b->{$sortfield}} @recs;
}

sub usercount {
    my $rec = shift;

    if ($$rec{users}) {
	return $$rec{users};
    } else {
	my $count = $persons->count("placeid = ?", $$rec{name});
	return $count;
    }	
}

sub competitionrank {
    my $rec = shift;
    if ($rec->{type} eq "country" && $rec->{users} > 0) {
	if (!$competitionrankloaded) {
	    require "../temp/countrydata.pl";
	    my $x;
	    # Make a density-ranked list
	    for $x (keys(%$country)) {
		my $c = $country->{$x};
		if ($c->{population} > 0) {
		    $c->{density} = $c->{"usercount"} / $c->{population};
		} 
		# tidying....
		$c->{name} = $x;
	    }
	    my $ix = 1;
	    for $x (sort {$country->{$b}->{density} <=> $country->{$a}->{density}}
		    keys(%$country)) {
		$rank2id[$ix] = $country->{$x};
		$rank{$x} = $ix++;
	    }
	    $competitionrankloaded = 1;
	}
	my $myrank = $rank{$rec->{name}};
	my $myc = $country->{$rec->{name}};
	printf OUT "$$rec{longname} <?php print _(\"is no.\") ?> $myrank <?php print _(\"in the density statistics, with\") ?> %5.2f <?php print _(\"users/Mpop\") ?><br>\n",
	$myc->{density};
	if ($myrank > 1) {
	    my $nextc = $rank2id[$myrank-1];
	    my $need = int($nextc->{density} * $myc->{population} - $myc->{"usercount"}) + 1;
	    
	    print OUT "$$rec{longname} <?php print _(\"needs\") ?> $need <?php print _(\"more users to pass\") ?> ",
	    urlname($nextc), " <?php print _(\"and become no.\")?> ", $myrank-1, "<br>\n";
	}
	if ($rank2id[$myrank+1]) {
	    my $prevc = $rank2id[$myrank+1];
	    my $need = int($myc->{density} * $prevc->{population} - $prevc->{"usercount"}) + 1;
	    print OUT urlname($prevc), " <?php print _(\"needs\") ?> $need <?php print _(\"more users to pass\") ?> ", $rec->{longname}, " <?php print _(\"and push it to no.\") ?> ", $myrank+1, "<br>\n";
	}
    }
}

sub maintainer {
    my $rec = shift;
    my ($userid, $pers);
    my @userids = split(" ", $$rec{maintainer});
    if ($#userids > -1) {
	if ($#userids > 0) {
	    print OUT "<?php print _(\"Maintainers\") ?>:<br>";
	} else {
	    print OUT "<?php print _(\"Maintainer\") ?>: ";
	}
	for $userid (@userids) {
	    $pers = $persons->get($userid);
	    if ($pers) {
                my $my_email = $pers->{email};
                # $my_email =~ s/@/&#x40;/g;
                print OUT $pers->{name}, " &lt;",
                   "<?php print emailCloaking(\"$my_email\")?>",
                      "&gt;<br>\n";
                #print OUT $pers->{name}, " &lt;",
                #   "<a href=\"mailto:$$pers{email}\">",
                #      $pers->{email}, "</a>&gt;<br>\n";
	    } else {
		print OUT "--$userid--<br>";
	    }
	}
    }
}


sub urlname {
# return a string containing an URL to a countryinfo document
    my $rec = shift;
    my $str;

    my $longname = $rec->{longname};
    $longname = "<i>nameless</i>" if !$longname;
    my $name = urlquote($rec->{name});
    if (isa($rec, "FileTable::Record")) {
	$str = sprintf("<a href=\"%s.php\">%s</a>",
		       $name, $longname);
    } else {
	$str = sprintf("<a href=\"%s.php\">%s</a>",
                   $name, $longname);
    }
}

sub urlquote {
    my $name = shift;
    $name =~ s/ /+/g;
    $name =~ s/\,/%2C/g;
    return $name;
}
